import os
import sys

import cv2
import numpy as np
import tensorflow as tf
from PIL import Image
from object_detection.utils import label_map_util, visualization_utils as vis_util
from tensorflow.python.lib.io.file_io import FileIO

# cap = cv2.VideoCapture('rtsp://admin:a1234567@192.168.1.68:554/h264/ch1/main/av_stream')
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
# cap = cv2.VideoCapture('1.mp4')

# The area size for detection, filter all the boxes outside the area.
area_xmin, area_ymin, area_xmax, area_ymax = 50, 50, 1230, 670

sys.path.append("..")

# What machine-learning-training to download.
# MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
# MODEL_FILE = MODEL_NAME + '.tar.gz'
# DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual machine-learning-training that is used for the object detection.
PATH_TO_CKPT = 'models/mobile_netv2_frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'pet_label_map.pbtxt')

NUM_CLASSES = 90

# opener = urllib.request.URLopener()
# opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# tar_file = tarfile.open(MODEL_FILE)
# for file in tar_file.getmembers():
#     file_name = os.path.basename(file.name)
#     if 'frozen_inference_graph.pb' in file_name:
#         tar_file.extract(file, os.getcwd())

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with FileIO(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')
        label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
        categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
                                                                    use_display_name=True)
        category_index = label_map_util.create_category_index(categories)


def convert_image_data_to_numpy_array(data, im_height, im_width):
    return np.array(data).reshape(
        (im_height, im_width, 3)).astype(np.uint8)


def convert_image_array_to_image(image_array, image_name):
    new_image = Image.fromarray(image_array, "RGB")
    new_image.save(image_name)


def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return convert_image_data_to_numpy_array(image.getdata(), im_height, im_width)


with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
        detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        while cap.isOpened():
            ret, frame = cap.read()
            image_np = frame
            # Expand dimensions since the machine-learning-training expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(image_np, axis=0)
            # Actual detection.
            (boxes, scores, classes, num) = sess.run(
                [detection_boxes, detection_scores, detection_classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})
            # Visualization of the results of a detection.

            # if filtered_boxes.__len__() > 0 and filtered_scores.__len__() > 0:
            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=5)
            # plt.figure(figsize=IMAGE_SIZE)
            cv2.imshow('frame', image_np)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()
